// pages/admin/notice/detail/detail.js
const app = getApp();

Page({
  data: {
    noticeId: null,
    notice: {},
    formattedContent: '',
    isLoading: true,
    errorMsg: ''
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        noticeId: options.id
      });
      this.loadNoticeDetail();
    } else {
      this.setData({
        isLoading: false,
        errorMsg: '通知ID不存在'
      });
    }
  },

  // 加载通知详情
  loadNoticeDetail: function() {
    this.setData({
      isLoading: true,
      errorMsg: ''
    });

    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/admin/notices/${this.data.noticeId}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('获取通知详情响应:', res);
        
        if (res.statusCode === 200) {
          // 处理通知内容，将换行符转换为<br>标签
          let formattedContent = '';
          if (res.data.content) {
            formattedContent = res.data.content
              .replace(/\n/g, '<br>')
              .replace(/\r/g, '');
          }
          
          // 确保附件是数组
          let attachments = [];
          if (res.data.attachments) {
            if (typeof res.data.attachments === 'string') {
              try {
                attachments = JSON.parse(res.data.attachments);
              } catch (e) {
                console.error('解析附件JSON失败:', e);
              }
            } else if (Array.isArray(res.data.attachments)) {
              attachments = res.data.attachments;
            }
          }
          
          // 确保目标角色是数组
          let targetRoles = [];
          if (res.data.targetRoles) {
            if (typeof res.data.targetRoles === 'string') {
              try {
                targetRoles = JSON.parse(res.data.targetRoles);
              } catch (e) {
                console.error('解析目标角色JSON失败:', e);
              }
            } else if (Array.isArray(res.data.targetRoles)) {
              targetRoles = res.data.targetRoles;
            }
          }
          
          this.setData({
            notice: {
              ...res.data,
              attachments: attachments,
              targetRoles: targetRoles
            },
            formattedContent: formattedContent,
            isLoading: false
          });
        } else {
          this.setData({
            isLoading: false,
            errorMsg: res.data.message || '获取通知详情失败'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({
          isLoading: false,
          errorMsg: '网络连接失败，请检查网络'
        });
      }
    });
  },

  // 下载附件
  downloadAttachment: function(e) {
    const { url, name } = e.currentTarget.dataset;
    if (!url) {
      wx.showToast({
        title: '附件链接无效',
        icon: 'none'
      });
      return;
    }
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const fullUrl = url.startsWith('http') ? url : `${serverUrl}${url}`;
    
    wx.showLoading({
      title: '正在下载...',
    });
    
    // 在小程序中，我们只能打开文件预览，不能直接下载
    wx.downloadFile({
      url: fullUrl,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            success: function() {
              console.log('打开文档成功');
            },
            fail: function(error) {
              console.error('打开文档失败:', error);
              wx.showToast({
                title: '无法打开此类型文件',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('下载失败:', err);
        wx.showToast({
          title: '下载失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },

  // 编辑通知
  editNotice: function() {
    wx.navigateTo({
      url: `/pages/admin/notice/edit/edit?id=${this.data.noticeId}`
    });
  },

  // 删除通知
  deleteNotice: function() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条通知吗？删除后无法恢复。',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.performDelete();
        }
      }
    });
  },

  // 执行删除操作
  performDelete: function() {
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.showLoading({
      title: '删除中...',
    });
    
    wx.request({
      url: `${serverUrl}/api/admin/notices/${this.data.noticeId}`,
      method: 'DELETE',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200 || res.statusCode === 204) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 返回上一页并刷新
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '删除失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },

  // 分享
  onShareAppMessage: function() {
    return {
      title: this.data.notice.title || '通知详情',
      path: `/pages/common/notice-detail/notice-detail?id=${this.data.noticeId}`
    };
  }
});